import React from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  StyleSheet,
  Dimensions,
  Platform,
  Pressable,
} from 'react-native';
import { Video, ResizeMode } from 'expo-av';
import { Audio } from 'expo-av';
import { MaterialIcons } from '@expo/vector-icons';
import { useRouter, useFocusEffect } from 'expo-router';
import { useTheme } from '../theme/ThemeContext';
import { ArtworkResponse } from '../../utils/api/types';
import * as Linking from 'expo-linking';
import { GestureDetector, Gesture } from 'react-native-gesture-handler';
import Animated, { 
  useAnimatedStyle, 
  useSharedValue,
  withSpring,
  runOnJS
} from 'react-native-reanimated';
import { formatDate } from '../../utils/date';
import { getFullURL, addTimestamp } from '../../utils/url';

const { width, height } = Dimensions.get('window');
const ITEM_HEIGHT = height * 0.8;

interface ExploreArtworkCardProps {
  artwork: ArtworkResponse;
}

export default function ExploreArtworkCard({ artwork }: ExploreArtworkCardProps) {
  const { theme } = useTheme();
  const router = useRouter();
  const [sound, setSound] = React.useState<Audio.Sound>();
  const [isPlaying, setIsPlaying] = React.useState(false);
  const videoRef = React.useRef<Video>(null);
  
  // 手势动画值
  const translateX = useSharedValue(0);

  // 处理导航
  const handlePress = () => {
    router.push({
      pathname: '/artwork/[id]',
      params: { id: artwork.id }
    });
  };

  // 监听页面焦点，重置动画状态
  useFocusEffect(
    React.useCallback(() => {
      // 当页面获得焦点时重置位置
      translateX.value = withSpring(0);
    }, [])
  );

  // 滑动手势
  const gesture = Gesture.Pan()
    .activeOffsetX(-10) // 只有当水平滑动超过10像素时才激活
    .onUpdate((event) => {
      if (event.translationX < 0) {
        translateX.value = event.translationX;
      }
    })
    .onEnd((event) => {
      if (event.translationX < -width * 0.2) {
        translateX.value = withSpring(-width * 0.8);
        runOnJS(handlePress)();
      } else {
        translateX.value = withSpring(0);
      }
    });

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: translateX.value }],
  }));

  // 处理音频播放
  async function handleAudioPlayback() {
    try {
      if (sound) {
        if (isPlaying) {
          await sound.pauseAsync();
          setIsPlaying(false);
        } else {
          await sound.playAsync();
          setIsPlaying(true);
        }
      } else {
        // 初始化音频系统
        await Audio.setAudioModeAsync({
          playsInSilentModeIOS: true,
          staysActiveInBackground: false,
          shouldDuckAndroid: true,
          playThroughEarpieceAndroid: false
        });

        // 加载并播放音频
        const { sound: newSound } = await Audio.Sound.createAsync(
          { uri: getFullURL(artwork.file_url) },
          { shouldPlay: true }
        );
        
        // 监听播放完成事件
        newSound.setOnPlaybackStatusUpdate((status) => {
          if (status.isLoaded) {
            if (status.didJustFinish) {
              setIsPlaying(false);
            }
          }
        });

        setSound(newSound);
        setIsPlaying(true);
      }
    } catch (error) {
      console.error('音频播放错误:', error);
      // 重置状态
      setIsPlaying(false);
      if (sound) {
        await sound.unloadAsync();
        setSound(undefined);
      }
    }
  }

  // 页面焦点变化时暂停媒体播放
  useFocusEffect(
    React.useCallback(() => {
      return () => {
        if (sound) {
          sound.pauseAsync();
          setIsPlaying(false);
        }
      };
    }, [sound])
  );

  // 页面卸载时清理资源
  React.useEffect(() => {
    return () => {
      if (sound) {
        sound.unloadAsync();
        setSound(undefined);
        setIsPlaying(false);
      }
    };
  }, [sound]);

  // 处理代码文件下载
  const handleCodeDownload = () => {
    Linking.openURL(artwork.file_url);
  };

  // 渲染媒体内容
  const renderContent = () => {
    const fileUrl = addTimestamp(getFullURL(artwork.file_url));

    switch (artwork.file_type) {
      case 'text':
        return (
          <View style={styles.textContainer}>
            <Text style={[styles.description, { color: theme.colors.text }]} numberOfLines={3}>
              {artwork.description}
            </Text>
          </View>
        );

      case 'image':
        return (
          <View style={styles.mediaWrapper}>
            <Image
              source={{ uri: fileUrl }}
              style={styles.media}
              resizeMode="cover"
            />
            <View style={styles.overlay}>
              <MaterialIcons name="image" size={24} color="white" />
            </View>
          </View>
        );

      case 'video':
        return (
          <View style={styles.mediaWrapper}>
            <Video
              ref={videoRef}
              source={{ uri: fileUrl }}
              style={styles.media}
              useNativeControls
              resizeMode={ResizeMode.COVER}
              shouldPlay={false}
              isLooping={false}
            />
            <View style={styles.overlay}>
              <View style={styles.playIconContainer}>
                <MaterialIcons name="play-circle-filled" size={48} color="white" />
              </View>
            </View>
          </View>
        );

      case 'audio':
        return (
          <View style={styles.audioWrapper}>
            <TouchableOpacity 
              style={styles.audioContainer} 
              onPress={handleAudioPlayback}
            >
              <MaterialIcons
                name={isPlaying ? 'pause-circle-filled' : 'play-circle-filled'}
                size={48}
                color={theme.colors.primary}
              />
              <Text style={[styles.audioText, { color: theme.colors.text }]}>
                {isPlaying ? '暂停' : '播放'}音频
              </Text>
            </TouchableOpacity>
            <View style={styles.audioWaveform}>
              {/* 可以添加音频波形图 */}
            </View>
          </View>
        );

      case 'code':
        return (
          <View style={styles.codeWrapper}>
            <TouchableOpacity 
              style={styles.codeContainer} 
              onPress={handleCodeDownload}
            >
              <MaterialIcons name="code" size={48} color={theme.colors.primary} />
              <Text style={[styles.codeText, { color: theme.colors.text }]}>
                查看代码
              </Text>
            </TouchableOpacity>
          </View>
        );

      default:
        return (
          <View style={styles.placeholderContainer}>
            <MaterialIcons name="insert-drive-file" size={48} color={theme.colors.primary} />
          </View>
        );
    }
  };

  return (
    <GestureDetector gesture={gesture}>
      <Animated.View style={[styles.container, animatedStyle]}>
        <TouchableOpacity
          style={[styles.card, { backgroundColor: theme.colors.card }]}
          onPress={handlePress}
        >
          {renderContent()}
          
          <View style={styles.infoContainer}>
            <Text style={[styles.title, { color: theme.colors.text }]} numberOfLines={2}>
              {artwork.title}
            </Text>
            <Text style={[styles.date, { color: theme.colors.placeholder }]}>
              {formatDate(artwork.created_at)}
            </Text>
            
            <View style={styles.tagsContainer}>
              {artwork.tags?.map((tag, index) => (
                <View
                  key={index}
                  style={styles.tag}
                >
                  <Text style={styles.tagText}>
                    {tag}
                  </Text>
                </View>
              ))}
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>
    </GestureDetector>
  );
}

const styles = StyleSheet.create({
  container: {
    width: width - 32, // 两侧各留 16 的间距
    height: (width - 32) * 1.5,
    alignSelf: 'center', // 确保居中
    marginVertical: 8,
  },
  card: {
    flex: 1,
    borderRadius: 12,
    overflow: 'hidden',
  },
  textContainer: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
  },
  mediaWrapper: {
    flex: 1,
  },
  media: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover', // 改为 cover 以填充容器
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  playIconContainer: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  placeholderContainer: {
    aspectRatio: 16 / 9,
    justifyContent: 'center',
    alignItems: 'center',
  },
  infoContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    padding: 16,
    paddingBottom: 20,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 10,
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  description: {
    fontSize: 14,
    color: '#fff',
    marginBottom: 10,
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  date: {
    fontSize: 12,
    color: '#fff',
    marginTop: 5,
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  tagsContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 5,
  },
  tag: {
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderRadius: 15,
    marginRight: 5,
    marginBottom: 5,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
  },
  tagText: {
    fontSize: 12,
    color: '#fff',
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  audioWrapper: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  audioContainer: {
    alignItems: 'center',
  },
  audioText: {
    marginTop: 8,
    fontSize: 16,
    color: '#fff',
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  audioWaveform: {
    width: '100%',
    height: 60,
    marginTop: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 8,
  },
  codeWrapper: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  codeContainer: {
    alignItems: 'center',
  },
  codeText: {
    marginTop: 8,
    fontSize: 16,
    color: '#fff',
    textShadowColor: 'rgba(0, 0, 0, 0.75)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  hint: {
    display: 'none',
  },
  hintText: {
    display: 'none',
  },
}); 